<!--
 * @Author: 张天昊
 * @Date: 2024-05-29 14:20:30
 * @LastEditTime: 2024-10-31 10:00:35
 * @LastEditors: 张天昊
 * @Description: 文件预览
 * @FilePath: /sentiment-dispose-app/src/components/FilePreviewer/FilePreviewer.vue
-->
<script>
import {
  defineComponent,
  watch,
  ref,
  computed,
  onUnmounted,
  getCurrentInstance
} from 'vue'
import Teleport from 'vue2-teleport'
import { createRuntimePreviewer } from '@/utils/Previewer'
import { px2vw } from '@/utils/helper'

export default defineComponent({
  components: {
    Teleport
  },
  setup(_, { expose }) {
    const slotId = `file-previewer-slot-${
      getCurrentInstance() ? getCurrentInstance().uid : Date.now()
    }`
    const RuntimePreviewerCtor = createRuntimePreviewer()
    const previewer = RuntimePreviewerCtor
      ? new RuntimePreviewerCtor(slotId)
      : null

    const show = ref(false)
    const el = ref()

    watch(show, (v) => {
      if (!v && previewer && previewer.player) {
        previewer.player.pause()
      }
    })

    const closeIconStyle = computed(() => {
      // return { top: `calc(${px2rem(20)} + ${`${deviceInfo.navHeight}px`})` }
      return {
        top: px2vw(20)
      }
    })

    onUnmounted(() => {
      previewer && previewer.destroy()
    })

    function preview(fileType, url) {
      if (previewer) {
        const result = previewer.preview(fileType, url)
        console.log(result)
        if (result) {
          show.value = true
        }
      }
    }
    expose({
      preview
    })
    return {
      slotId,
      el,
      closeIconStyle,
      show
    }
  }
})
</script>

<template>
  <Teleport to="body">
    <van-overlay :z-index="3000" :show="show" @click="show = false">
      <div class="relative h-screen w-screen" @click.stop>
        <van-icon
          :size="$px2vw(20)"
          name="close"
          class="absolute right-20px z-1 text-white"
          @click="show = false"
        />
        <div
          :id="slotId"
          ref="el"
          class="absolute bottom-0 left-0 right-0 top-0"
        />
      </div>
    </van-overlay>
  </Teleport>
</template>
